package com.weathereport.activity;

import java.util.ArrayList;
import java.util.List;

import com.weathereport.R;
import com.weathereport.activity.adapter.WeatheReportMainAdapter;
import com.weathereport.dao.WeatherDAO;
import com.weathereport.entity.Armario;
import com.weathereport.entity.Local;
import com.weathereport.entity.Forecast;
import com.weathereport.helper.Checker;
import com.weathereport.listener.GPSListener;
import com.weathereport.ws.WeatherWS;

import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class WeatheReportMain extends ListActivity implements OnClickListener{

	private Context ctx;
	private Intent nav;
	private LocationManager locationManager;
	private LocationListener locationListener = new GPSListener();
	private int selectedItem;
	private WeatherDAO dao;
	private ListView listView;
	private List<Local> locals;
	private Time today;
	private Local local;
	private ProgressDialog progressDialog;
	private Handler handler = new Handler();
	private boolean updated;
	private String todayDate;
	private int qntLocals;	
	private boolean firstRun = true;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		ctx = this;
		
		firstRun = getIntent().getBooleanExtra("firstRun", true);
		
		SharedPreferences settings = getSharedPreferences("prefs", 0);
        SharedPreferences.Editor editor = settings.edit();

        editor.putString("authorizationWeather", "db7baa2566534885");
        editor.putString("authorizationPlaces", "AIzaSyC4-XeOlxc2DAPW3uBDndXHw-e0PQ4IsnM");
        editor.commit();
        
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationListener);
 		
 		dao = new WeatherDAO(ctx); 		

 		Armario.createInstance();
 		
 		today = new Time(Time.getCurrentTimezone());
		today.setToNow();		
		
		todayDate = today.monthDay + "/" + getMonth(today.month) + "/" + today.year;
		
		updated = dao.isUpdated(todayDate);
		qntLocals = dao.getCountlocal();
		
		if (Checker.isOnline(ctx)){
			
			if (qntLocals > 0){
				
				if (updated == false){			
					
					nav = new Intent(ctx, WeatheReportMain.class);
					nav.putExtra("firstRun", false);
					
					startProgressDialog(getResources().getString(R.string.msgUpdateProgressTitle), getResources().getString(R.string.msgUpdateProgressMessage));
					
					new Thread(){
						
						public void run(){
						
							try {
								
								List<Forecast> forecast = new ArrayList<Forecast>();
				
								WeatherDAO dao = new WeatherDAO(ctx);
								List<Local> locals = new ArrayList<Local>();
								locals = dao.localList();
								
								WeatherWS ws = new WeatherWS();
				
								for (int i = 0; i < locals.size(); i++) {
									forecast = ws.getForecast(ctx, locals.get(i));
									locals.get(i).setForecast(forecast);
									
									dao.saveOrUpdateLocal(locals.get(i), 1);					
								}
								
								Looper.prepare();
								handler.post(new Runnable() {
									
									public void run() {
										
										Toast.makeText(ctx, R.string.msgUpdateSuccess, Toast.LENGTH_SHORT).show();
										refreshActivity(nav);
									}
								});													
							} catch (Exception e) {
								// TODO - fazer tratamento de erros aqui
							} finally {
								
								finishProgressDialog();							
							}
						}					
					}.start();
				}
			}
		} else {			
			
			dao.removePastDates(today.monthDay + "/" + getMonth(today.month) + "/" + today.year);
			
			if (firstRun){
				alertErrorOperation(ctx);
			}
		}
				
		locals = dao.localList();
		
		listView = getListView();		
		setListAdapter((new WeatheReportMainAdapter(this, locals)));
				
		// Enable filter feature
		listView.setTextFilterEnabled(true); 		
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

    	menu.add(Menu.NONE, 0, 0, R.string.addMenu);
    	menu.add(Menu.NONE, 1, 1, R.string.updMenu);
    	menu.add(Menu.NONE, 2, 2, R.string.stgMenu);
 		
 		return super.onCreateOptionsMenu(menu);    	
    }
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	
		switch (item.getItemId()) {
		case 0:
			if(Checker.isOnline(ctx)){
			
				alertTypeInsertion(ctx);
			} else {
				
	    		alertErrorConnection(ctx);    		
			}	
			
			return true;			
		case 1:
			if(Checker.isOnline(ctx)){
									
				nav = new Intent(ctx, WeatheReportMain.class);
				nav.putExtra("firstRun", false);
				
				startProgressDialog(getResources().getString(R.string.msgUpdateProgressTitle), getResources().getString(R.string.msgUpdateProgressMessage));
				
				new Thread(){
					
					public void run(){
					
						try{
							
						List<Forecast> forecast = new ArrayList<Forecast>();
		
						WeatherDAO dao = new WeatherDAO(ctx);
						List<Local> locals = new ArrayList<Local>();
						locals = dao.localList();
						
						WeatherWS ws = new WeatherWS();
		
						for (int i = 0; i < locals.size(); i++) {
							forecast = ws.getForecast(ctx, locals.get(i));
							locals.get(i).setForecast(forecast);
							
							dao.saveOrUpdateLocal(locals.get(i), 1);					
						}
						
						Looper.prepare();
						handler.post(new Runnable() {
							
							public void run() {
								
								Toast.makeText(ctx, R.string.msgUpdateSuccess, Toast.LENGTH_SHORT).show();
								refreshActivity(nav);
							}
						});													
						}catch (Exception e){
						
						}finally {
							
							finishProgressDialog();							
						}
					}					
				}.start();
			}else{
				
				alertErrorConnection(ctx);
			}
			
			return true;
		case 2:
			
			nav = new Intent(ctx, SettingsActivity.class);
			startActivity(nav);
			
			return true;		
		default:
			break;
		}
    	
		return super.onOptionsItemSelected(item);
	}
    
    public void startAddCityActivity(int type){
    	    	
    	nav = new Intent(this, AddLocalActivity.class);
    	nav.putExtra("selectType", type);
    	
    	if (type == 1){
    		
    		if (GPSListener.getLatitude() == 0 && GPSListener.getLongitude() == 0){
    			
    			alertErrorGps(ctx);
    		}else {
    			
    			startActivity(nav);
    		}
    	}else {
    	    	
    		startActivity(nav);
    	}
    }       
    
    public int getMonth(int month){
    	
    	int rightMonth = 0;
    	
    	switch (month) {
		case 0:
			rightMonth = 1;
			break;
		case 1:
			rightMonth = 2;
			break;
		case 2:
			rightMonth = 3;
			break;
		case 3:
			rightMonth = 4;
			break;
		case 4:
			rightMonth = 5;
			break;
		case 5:
			rightMonth = 6;
			break;
		case 6:
			rightMonth = 7;
			break;
		case 7:
			rightMonth = 8;
			break;
		case 8:
			rightMonth = 9;
			break;
		case 9:
			rightMonth = 10;
			break;
		case 10:
			rightMonth = 11;
			break;
		case 11:
			rightMonth = 12;
			break;
		default:
			break;
		}
    	
    	return rightMonth;
    }
    
    @Override
 	public void onStop(){
 		super.onStop();
 		locationManager.removeUpdates(this.locationListener);
 	}

 	@Override
 	public void onResume(){
 		super.onResume();
 		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationListener);
 	}
 	
 	@Override
 	public void onRestart(){
 		super.onResume();
 		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationListener);
 	}

	public void onClick(View v) {
		
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		
		alertSelectView(ctx, position, l);
	}
	
	public void onBackPressed(){
 		
		moveTaskToBack(true);
 	}
	
	protected void startProgressDialog(final String headerMessage, final String message) {
		
		progressDialog = ProgressDialog.show(this, headerMessage, message, false, true);
	}

	protected void finishProgressDialog() {
		
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}
	
	private void refreshActivity(Intent intent){
		
		finish();
		startActivity(intent);
	}
	
	public void alertErrorOperation(Context context){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);		
		builder.setTitle(R.string.errorOperationTitle);
		builder.setMessage(R.string.errorOperationMessage);
		builder.setPositiveButton(R.string.alertOkBT, new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
	
	public void alertSelectView(Context context, final int position, final ListView l){
		
		ArrayAdapter<CharSequence> items = new ArrayAdapter<CharSequence>(ctx, R.layout.dialogtype, getResources().getStringArray(R.array.action));
    	 
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.adgSelectActionTitle);        
        builder.setAdapter(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {

            	local = (Local) l.getAdapter().getItem(position);
            	switch (item) {
               		case 0:
										
               			if (local.getForecast().size() > 0){
               				
               				nav = new Intent(ctx, ClothesIndicationActivity.class);
    		        		nav.putExtra("localId", local.getId());
    		        		startActivity(nav);
               			}else {
               				
               				alertErrorNoData(ctx);
               			}		        		
					break;
               		case 1:
										
               			if (local.getForecast().size() > 0){
               				nav = new Intent(ctx, LocalForecastActivity.class);
    		        		nav.putExtra("localId", local.getId());
    		        		startActivity(nav);
               			}else {
               				
               				alertErrorNoData(ctx);
               			}		        		
	        		break;
               		case 2:
				
               			startProgressDialog(getResources().getString(R.string.msgDelProgressTitle), getResources().getString(R.string.msgDelProgressMessage));
				
               			new Thread(){
					
               				public void run(){
					
               					try{
               						dao.delete(local);
				
									Looper.prepare();
									handler.post(new Runnable() {
										
										public void run() {
											
											Toast.makeText(ctx, R.string.msgDeleteSuccess, Toast.LENGTH_SHORT).show();
											goToMain();
										}
									});
								}catch(Exception e){
							
								}finally{
									finishProgressDialog();
								}
               				}
               			}.start();
           			break;
               		default:
           			break;
            	}
            }
        });
                
        builder.create().show();
	}
	
	public void alertErrorConnection(Context context){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(R.string.errorWithOutConnection);
		builder.setPositiveButton(R.string.alertOkBT, new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				
				dialog.dismiss();					
			}
		});	
		builder.create().show();
	}
	
	public void alertErrorGps(Context context){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(R.string.errorGpsNotSync);
		builder.setPositiveButton(R.string.alertOkBT, new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
	
	public void alertErrorNoData(Context context){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(R.string.noData);
		builder.setPositiveButton(R.string.alertOkBT, new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
	
	public void alertTypeInsertion(Context context) {

    	ArrayAdapter<CharSequence> items = new ArrayAdapter<CharSequence>(context, R.layout.dialogtype, getResources().getStringArray(R.array.type));
    	
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.adgSelectTypeTitle);        
        builder.setAdapter(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item)                   {

                selectedItem = item;
                startAddCityActivity(selectedItem);
            }
        });
                
        builder.create().show();
    }
	
	private void goToMain(){
		
		nav = new Intent(ctx, WeatheReportMain.class);
		nav.putExtra("firstRun", false);
		startActivity(nav);		
	}
}
